﻿namespace Mockingbird.MVC.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Core.Infrastructure.Logging.Interfaces;
    using Core.Models;
    using Core.Repository;
    using Infrastructure.BaseTypes;
    using System.Web.Mvc;
    using MongoDB.Bson;

    public class UserController : BaseController
    {
        private readonly IAccountRepository accountRepository;

        public UserController(ILogger logger, IAccountRepository accountRepository)
            : base(logger)
        {
            this.accountRepository = accountRepository;
        }

        public ActionResult Search(string username)
        {
            if (username.Contains('#'))
            {
                return RedirectToAction("GetHashTags", "NewsFeed", new { searchText = username });
            }

            var users = accountRepository.SearchUsers(username);

            return View(users);
        }

        public void Follow(string userId)
        {
            if (User.Properties.Id.ToString() != userId && !User.Properties.Friends.Select(s => s.ToString()).ToList().Contains(userId))
            {
                var newState = accountRepository.FollowUser(User.Properties.Id, userId);

                if (newState != null)
                {
                    User.Properties = newState;
                }
                else
                {
                    throw new Exception("Wrong user");
                }
            }
        }

        public void Unfollow(string userId)
        {
            if (User.Properties.Id.ToString() != userId && User.Properties.Friends.Select(s => s.ToString()).ToList().Contains(userId))
            {
                var newState = accountRepository.UnfollowUser(User.Properties.Id, userId);

                if (newState != null)
                {
                    User.Properties = newState;
                }
                else
                {
                    throw new Exception("Wrong user");
                }
            }
        }

        public ActionResult GetFriends()
        {
            var friends = new List<UserPropertiesModel>();

            if (User.Properties.Friends != null)
            {
                foreach (var friend in User.Properties.Friends)
                {
                    friends.Add(accountRepository.GetUserById(friend.ToString()));
                }
            }

            return View("Search", friends);
        }
    }
}
